Python Basics

Datastructures

First we start with something lazy that doesen't do anything, a comment.


In [1]:
# This is a python comment

Strings


In [2]:
my_string = "Foo"
another_string = 'bar'

new_string = my_string +' '+ another_string

In [3]:
print(new_string)


Foo bar

Numbers

Python supports all kinds of numbers. One little pifall is that numbers without a decimal point are interpreted as integers.


In [4]:
pi =  3.1415
x = 3
y = 3.
z = (1.5 + 5j)

print type(pi)
print type(x)
print type(y)
print type(z)


<type 'float'>
<type 'int'>
<type 'float'>
<type 'complex'>

In [5]:
import math
import cmath

print pi*x+11.0
print x**2
print math.sqrt(3)
print cmath.sqrt(-3)


20.4245
9
1.73205080757
1.73205080757j

Lists

A list is similar to an array in C or Matlab. But it offers a lot more functionalites.


In [6]:
my_empty_list = []
musicians = ['Chris', 'Kurt', 'Dave']
instruments = ['Drums', 'Vocals', 'Guitar']
print musicians


['Chris', 'Kurt', 'Dave']

What makes lists powerful are the built in methods of lists


In [7]:
print len(musicians)
print zip(musicians, instruments)
print musicians * 3

def is_odd(num):
   return num % 2

print filter(is_odd, range(0,10,1),)


3
[('Chris', 'Drums'), ('Kurt', 'Vocals'), ('Dave', 'Guitar')]
['Chris', 'Kurt', 'Dave', 'Chris', 'Kurt', 'Dave', 'Chris', 'Kurt', 'Dave']
[1, 3, 5, 7, 9]

In [8]:
musicians.append('Heino')
print musicians


['Chris', 'Kurt', 'Dave', 'Heino']

Dictionaries

Dictionaries are in other languages called Map or hashmap. A dict contains keys and values


In [9]:
empty_dict = {}
print type(empty_dict)


<type 'dict'>

In [10]:
car = {'Brand': 'Volkswagen', 
       'Model': 'Golf', 
       'Power': 167.9,
       'Weight': 1500,
      'Serial_Number':0}

In [11]:
car.keys()


Out[11]:
['Weight', 'Brand', 'Model', 'Power', 'Serial_Number']

Acessing a dictionary


In [12]:
car['Model']


Out[12]:
'Golf'

Dataflow

if statement


In [20]:
name = raw_input('Write you name please: ')
if(len(name)< 5):
    print "Your Name is shorter than 5 Characters"
else:
    print "Your Name is 5 characters long or longer"


Write you name please: Peter
Your Name is 5 characters long or longer

For loops


In [16]:
for index in range(3):
    print index


0
1
2

In [21]:
my_cars = [{'Brand': 'Tesla', 
       'Model': 'Model-S', 
       'Power': 510.0,
       'Weight': 2100,
      'Serial_Number':0},{'Brand': 'Jaguar', 
       'Model': 'E-Type', 
       'Power': 210.1,
       'Weight': 1300,
      'Serial_Number':0}]

for car in my_cars:
    print car['Model']


Model-S
E-Type

In [18]:
for index, car in enumerate(my_cars):
    print('%s : %s - %s' %(index, car['Brand'], car['Model']))


0 : Tesla - Model-S
1 : Jaguar - E-Type

List comperhension


In [19]:
brands = [car['Brand'] for car in my_cars]
print brands


['Tesla', 'Jaguar']

Functions


In [ ]:
def myfunction(A, B):
    result = A + B
    return result

In [ ]:
myfunction(8, 9)

Default parameters.


In [ ]:
def myfunction_2(A, B, offset = 0):
    result = A + B + offset
    return result

In [ ]:
myfunction_2(10,5)

In [ ]:
myfunction_2(10,5, offset=100)

Anonymous functions ... The Lambda operator


In [ ]:
map(lambda x : x*2, [1,2,3])

Classes


In [ ]:
class Tree(object):
    def __init__(self):
        
        self.heigth = 0.2;
        self.leafs = [Leaf() for i in range(10)];
    
    def grow(self):
        self.heigth=self.heigth *1.5;
        
    def get_older(self):
        self.leafs = filter(lambda leaf: leaf.color != 'brown', self.leafs)

    def grow_leafs(self):
        self.leafs.extend([Leaf() for i in range(len(self.leafs))])
    
    def green_leafs(self):
        return filter(lambda leaf: leaf.color == 'green', self.leafs)
    
    def orange_leafs(self):
        return filter(lambda leaf: leaf.color == 'orange', self.leafs)

        
    def __str__(self):
        num_green_leafs = 100. * float(len(self.green_leafs()))/float(len(self.leafs))
        num_orange_leafs = 100. * float(len(self.orange_leafs()))/float(len(self.leafs))
        return "Tree: %2.1f m tall, %s leafs %2.1f %% green %2.1f orange" % (self.heigth, len(self.leafs), num_green_leafs, num_orange_leafs )
        
class Leaf(object):
    def __init__(self):
        self.color = 'green';
        
    def get_older(self):
        self.color = 'orange';
        
    def die(self):
        self.color = 'brown';

In [ ]:
my_tree = Tree()

In [ ]:
print my_tree

In [ ]:
for year in range(0,3,1):
    my_tree.grow()
    my_tree.grow_leafs()
    print my_tree

Exercise: Program the aging of the tee... 50 % of the leafs are getting older and 25% of the organge leafs die. Print the tree at every iteration.


In [ ]:
my_tree = Tree()

for year in range(0,10,1):
    my_tree.grow()
    my_tree.grow_leafs()
    print my_tree
    
print " Stopped growing"

for year in range(0,10,1):
    my_tree.get_older()
    for leaf in my_tree.green_leafs()[::2]:
            leaf.get_older()
    for leaf in my_tree.orange_leafs()[::3]:
            leaf.die()
    print my_tree

Crating plots


In [30]:
from bokeh.io import output_notebook, show
from bokeh.plotting import figure

output_notebook()


BokehJS successfully loaded.

In [49]:
k = range(0,1000,1)

In [50]:
plot = figure()
plot.line(range(100),k)
show(plot)


Out[50]:
<bokeh.io._CommsHandle at 0x10fb8a890>

In [ ]:


In [ ]:


In [ ]: